import { v4 as uuidv4 } from 'uuid';
import fs from 'fs'
import path from 'path'
export default {
  use(app, knex){
    //上传网关配置至网关服务器
    app.post('/gateway/upload', function(req, res){
      let gw1 = {};//网关信息
      let gw2 = {};//传输端信息
      let chanel = {}; //采集端信息
      let tag = []; //节点信息
      knex('gateway')
      .limit(1)
      .where('id', '=', req.body.id)
      .select('*')
      .then(rows=>{
        const row = rows[0]
        let gw1 = {nm: row.nm, sn: row.sn};
        delete row.nm;
        delete row.sn;
        delete row.id;
        for(let key in row ){
          if(row[key] !== undefined) gw2[key] = row[key]
        }
      })

      //采集端信息
      knex('chanel')
      .where('parent_id', '=', req.body.id)
      .select('*')
      .then(rows=>{
        rows.forEach(item => {
          chanel.type = item.type;
          chanel.protocol = item.protocl;
          
          delete item.type;
          delete item.protocl;
          delete item.id;
          
          let com = {};
          for(let key in item){
            if(item[key] !== undefined) com[key] = item.key;
          }

          if(!chanel.com) chanel.com = [com];
          else chanel.com.push(com)
        })
      })


      //节点信息
      knex('tag')
      .leftJoin('user_tag', 'tag.id', 'user_tag.tag_id')
      .leftJoin('device', 'tag.parent_id', 'device.id')
      .select('tag.nnm', 'tag.cd', 'tag.rsa', 'tag.dt', 'tag.rn', 'tag.rt', 'tag.rw', 'tag.id as nid', 'tag.ch', 'user_tag.user_id as uid', 'device.dnm', 'device.addr', 'device.shortb', 'device.intb', 'device.doubleb', 'device.strb')
      .then(rows => {
        res.send({
          code: 0,
          data: rows
        })
      })



    })


    //新增网关
    app.post('/gateway/add', function(req, res){
      knex('gateway')
      .where('name', '=', req.body.name)
      .then(rows => {
        if(rows.length > 0){
          res.send({
            code: 1,
            message: '网关名称重复请修改后重新提交',
          })
        }else{
          knex('gateway')
          .insert({id: uuidv4(), ...req.body})
          .then(row=>{
            res.send({
              code: 0,
              message: '新增网关成功'
            })
          })
          .catch(err=>{
            console.log(err)
            res.send({
              code: 1,
              message: err
            })
          })  
        }
      })
    })


    //查询网关
    app.post('/gateway', function(req, res){
      knex('gateway')
      // .where({user_id: req.user_id})
      .select('*').then(rows=>{
        res.send({
          code: 0,
          data: rows
        })
      })  
      .catch(err => {
        res.send({
          code: 1,
          message: err
        })
      })
    })

    
    //删除网关
    app.post('/gateway/del', function(req, res){
      knex
      .raw(`PRAGMA foreign_keys=ON`)
      .then(() => {
        knex
        .raw(`delete from gateway where id="${req.body.id}"`)
        .then( rows =>{
          res.send({
            code: 0,
            data: '删除网关成功'
          })
        })
      })
    })

    
    //更新网关
    app.post('/gateway/update', function(req, res){
      const data = req.body;
      const id = data.id;
      delete data.id;
      knex('gateway')
      .where('id', '=', id)
      .update({
        ...data
      })
      .then(row => {
        res.send({
          code: 0,
          data: '更新网关成功'
        })
      })
      .catch(err => {
        res.send({
          code: 1,
          message: err
        })
      })
    })


    //导出网关配置
    app.post('/gateway/export', function(req, res){
       const code = {
         'mqtt-client': 'mqttClient'
       }
       let gw = {
        [code[req.body.protocl]]: req.body
      }

      let chanels = []


      knex('chanel')
      .where('parent_id', '=', req.body.id)
      .select('*')
      .then(rows => {
        chanels = rows;

        chanels.forEach((cnl, i) => {
          knex('tag')
          .where('chanel_id', '=', cnl.id)
          .select('*')
          .then(tags => {
            chanels[i].nodes = tags;
            gw[code[req.body.protocl]].chanels = chanels;

            res.setHeader('Content-Type', 'application/octet-stream' )
            res.send({
              code: 0,
              data: gw
            })
          })
        });
      })






    })
  }
}

